#!/bin/bash

SRC_DIR=$1
BAK_DIR=$2
PREFIX_BAK_NAME=$3

echo "自动备份程序"

if [ -z "$BAK_DIR" -o -z "$BAK_DIR" -o -z "$PREFIX_BAK_NAME" ]; then
  echo "输入参数错误"
  return 0
fi

if [ ! -d $SRC_DIR ]; then
  echo "源目录不存在"
  return 0
fi

if [ ! -d $BAK_DIR ]; then
  echo "建立备份目录"
  mkdir -p $BAK_DIR
fi

if [ ! -d $BAK_DIR ]; then
  echo "备份目录不存在"
  return 0
fi

# define
dayofweek=`date "+%u"`
today=`date "+%Y%m%d"`
weekandyear=`date "+Y%YW%W"`
BAK_PATH="$BAK_DIR/$PREFIX_BAK_NAME/$weekandyear"
TAR_INFO="${PREFIX_BAK_NAME}-${weekandyear}"
#echo $TAR_INFO

if [ ! -d $BAK_PATH ]; then
  mkdir -p $BAK_PATH
fi

if [ ! -d $BAK_PATH ]; then
  echo "备份目录不存在"
  return 0
fi

if [ $dayofweek -eq 1 ]; then
  tar_file="${PREFIX_BAK_NAME}_full_${today}.tar.gz"
else
  tar_file="${PREFIX_BAK_NAME}_incr_${today}.tar.gz"
fi

cd $BAK_PATH

if [ ! -f "$tar_file" ]; then
  tar -g ${TAR_INFO} -zcf $tar_file $SRC_DIR
fi

